#include "mainWindow.hpp"
#include <QString>
#include <QMessageBox>
#include <QIntValidator>
#include <QEvent>
#include <QMouseEvent>

extern uint image_waitting_time; // 图片录制间隔，单位为毫秒
extern uint video_duration;      // 视频录制时长，单位为秒
extern uint video_fps;
extern uint max_video_frame_counter; // 最大视频帧数

QImage matToQImage(Mat &mat);
void format_camera_counter();
void format_http_counter();

MainWindow::MainWindow(QWidget *parent)
    : QWidget(parent)
{
    // 初始化组件
    QPushButton *btnSubmit = new QPushButton("提交修改");
    QPushButton *btnCancle = new QPushButton("取消修改");
    QPushButton *btnStart = new QPushButton("开始");
    QPushButton *btnSuspend = new QPushButton("暂停");
    QPushButton *btnRerun = new QPushButton("重新录制");
    label = new QLabel();
    updateLabel();
    video_label = new QLabel(this);
    interval_field = new QLineEdit(this);
    interval_field->setValidator(new QIntValidator(this));
    interval_field->setText(QString::number(image_waitting_time));
    duration_field = new QLineEdit(this);
    duration_field->setValidator(new QIntValidator(this));
    duration_field->setText(QString::number(video_duration));

    // 设置布局
    auto *layout = new QVBoxLayout(this);
    layout->addWidget(video_label, 5);
    layout->addWidget(label, 1);

    auto *field_layout = new QHBoxLayout(this);
    QLabel *interval_info = new QLabel("图片采集间隔：");
    QLabel *interval_unit = new QLabel("毫秒    ");
    field_layout->addWidget(interval_info, 0);
    field_layout->addWidget(interval_field, 0);
    field_layout->addWidget(interval_unit, 0);
    QLabel *duration_info = new QLabel("视频采集时长：");
    QLabel *duration_unit = new QLabel("秒");
    field_layout->addWidget(duration_info, 0);
    field_layout->addWidget(duration_field, 0);
    field_layout->addWidget(duration_unit, 0);
    layout->addLayout(field_layout, 0);

    auto *btnLayout = new QHBoxLayout();
    btnLayout->addWidget(btnStart, 0);
    btnLayout->addWidget(btnSuspend, 0);

    auto *submitLayout = new QHBoxLayout();
    submitLayout->addWidget(btnSubmit, 0);
    submitLayout->addWidget(btnCancle, 0);

    layout->addLayout(submitLayout, 0);
    layout->addLayout(btnLayout, 0);
    layout->addWidget(btnRerun, 0);
    setLayout(layout);

    // 设置事件
    connect(btnSubmit, &QPushButton::clicked, this, &MainWindow::resetCamera);
    connect(btnCancle, &QPushButton::clicked, this, &MainWindow::cancelReset);
    connect(btnStart, &QPushButton::clicked, this, &MainWindow::startThread);
    connect(btnSuspend, &QPushButton::clicked, this, &MainWindow::suspendThread);
    connect(btnRerun, &QPushButton::clicked, this, &MainWindow::rerunThread);
    connect(this, &MainWindow::frame_ready, this, &MainWindow::updateFrame);
    interval_field->installEventFilter(this);
    duration_field->installEventFilter(this);

    setWindowTitle("控制窗口");
    resize(600, 600);
    this->setFocus();
}

/**
 * 关闭窗口事件
 * @param event 关闭事件
 */
void MainWindow::closeEvent(QCloseEvent *event)
{
    running = false;
    event->accept();
    cout << "MainWindow closed" << endl;
}

/**
 * 重置摄像头，将图片录制间隔和视频录制时长重置
 */
void MainWindow::resetCamera()
{
    if (!suspend)
    {
        QMessageBox::warning(this, "警告", "当前线程未暂停，无法重置摄像头参数");
        return;
    }
    int temp_interval = interval_field->text().toInt();
    int temp_duration = duration_field->text().toInt();

    QMessageBox::StandardButton reply;
    string str = "你确定要修改参数吗？\n图片采集间隔：" + to_string(temp_interval) + "毫秒\n视频采集时长：" + to_string(temp_duration) + "秒";
    reply = QMessageBox::question(this, "确认操作", QString::fromStdString(str),
                                  QMessageBox::Yes | QMessageBox::No);

    if (reply == QMessageBox::Yes)
    {
        image_waitting_time = temp_interval;
        video_duration = temp_duration;
        max_video_frame_counter = video_duration * video_fps;
    }
    else
    {
        qDebug() << "cancel submit\n";
        return;
    }
}

/**
 * 取消重置摄像头的参数，将输入框的值恢复
 */
void MainWindow::cancelReset()
{
    interval_field->setText(QString::number(image_waitting_time));
    duration_field->setText(QString::number(video_duration));
}

void MainWindow::startThread()
{
    suspend = false;
    updateLabel();
}

void MainWindow::suspendThread()
{
    suspend = true;
    updateLabel();
}

/**
 * 重新录制，将视频和图像计数清零并初始化视频写入
 */
void MainWindow::rerunThread()
{
    if (suspend)
    {
        format_camera_counter();
        format_http_counter();
    }
    else
    {
        QMessageBox::warning(this, "警告", "当前线程未暂停，无法重新录制");
    }
}

/**
 * 更新状态标签
 */
void MainWindow::updateLabel()
{
    QString str = "当前状态：";
    if (suspend)
    {
        str += "暂停";
        label->setStyleSheet("color: red;");
    }
    else
    {
        str += "运行中";
        label->setStyleSheet("color: green;");
    }
    str += "\n";
    label->setText(str);
}

/**
 * 更新视频标签
 * @param frame opencv库传送来的Mat数据
 */
void MainWindow::updateFrame(Mat &frame)
{
    QImage image = matToQImage(frame);
    video_label->setPixmap(QPixmap::fromImage(image).scaled(video_label->size(), Qt::KeepAspectRatio));
}

/**
 * 转化mat数据为QImage
 * @param mat opencv库传送来的Mat数据
 * @return QImage
 */
QImage matToQImage(Mat &mat)
{
    if (mat.channels() == 3)
    {
        return QImage(mat.data, mat.cols, mat.rows, mat.step, QImage::Format_BGR888).copy();
    }
    else if (mat.channels() == 1)
    {
        return QImage(mat.data, mat.cols, mat.rows, mat.step, QImage::Format_Grayscale8).copy();
    }
    else
    {
        return QImage();
    }
}